<template>
  <common-list>
    <!-- <div class="app-container"> -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @enter="handleQuery"
        v-show="showSearch"
        label-width="90px"
      >
        <el-form-item label="敏感字段名称" prop="name">
          <common-input
            v-model="queryParams.name"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-form>
    </common-search>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['datascan:sensitivewords:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['datascan:sensitivewords:remove']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      v-loading="loading"
      slot="content"
      :data="wordsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="word_id" align="center" prop="wordId" /> -->
      <el-table-column
        label="敏感字段名称"
        align="left"
        prop="name"
        width="180"
      />
      <el-table-column
        label="固定长度"
        align="left"
        prop="length"
        width="180px"
      >
        <template slot-scope="scope">
          {{ scope.row.length ? scope.row.length : "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="长度范围"
        align="left"
        prop="maxLength"
        width="180px"
      >
        <template slot-scope="scope">
          {{
            !scope.row.length
              ? (typeof scope.row.minLength === "number"
                  ? scope.row.minLength
                  : "") +
                "-" +
                (typeof scope.row.maxLength === "number"
                  ? scope.row.maxLength
                  : "")
              : "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="正则表达式"
        align="left"
        prop="sensitiveContent"
        show-overflow-tooltip
      />
      <el-table-column label="状态" align="center" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === 0">启用</el-tag>
          <el-tag type="danger" v-if="scope.row.status === 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="160px">
        <template slot-scope="scope">
          <el-button type="text" @click="getWords(scope.row, 2)"
            >详情
          </el-button>
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datascan:sensitivewords:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
            v-hasPermi="['datascan:sensitivewords:edit']"
          >
            <span v-if="scope.row.status === 1">启用</span>
            <span v-if="scope.row.status === 0">停用</span>
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datascan:sensitivewords:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或编辑敏感字段对话框 -->
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :buttonLoading="buttonLoading"
      :infoLoading="infoUpdateLoading"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.native.prevent
      >
        <el-collapse accordion v-model="activeName">
          <el-collapse-item title="基础信息" name="1">
            <el-form-item label="敏感字段名称" prop="name">
              <common-input
                v-model="form.name"
                :maxlength="16"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="长度特征" name="2">
            <el-radio-group
              v-model="lengthType"
              @change="changeLengthType"
              style="margin-bottom: 10px"
            >
              <el-radio :label="0">固定长度</el-radio>
              <el-radio :label="1">长度范围</el-radio>
            </el-radio-group>
            <el-form-item
              v-if="lengthType === 0"
              label="固定长度"
              prop="length"
            >
              <common-input-number
                style="width: 100%"
                :max-length="6"
                v-model="form.length"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item
              v-if="lengthType === 1"
              label="长度范围"
              prop="fanwei"
            >
              <div class="lengthRang">
                <common-input-number
                  :max-length="6"
                  v-model="form.minLength"
                  style="width: 49%"
                  placeholder="请输入"
                />
                <span class="rangLine">-</span>
                <common-input-number
                  :max-length="6"
                  v-model="form.maxLength"
                  style="width: 49%"
                  placeholder="请输入"
                />
              </div>
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="字段特征" name="3">
            <div
              style="
                display: flex;
                align-items: center;
                color: #f56c6c;
                line-height: 14px;
                margin-bottom: 12px;
                margin-left: 25px;
                font-size: 12px;
              "
            >
              <span style="margin-right: 4px">说明:</span>
              <span>优先匹配排除,再匹配包含!</span>
            </div>
            <el-form-item label="字段名排除" prop="columnNameEx">
              <common-input
                v-model="form.columnNameEx"
                type="textarea"
                placeholder="优先匹配排除"
              />
            </el-form-item>
            <el-form-item label="字段名包含" prop="columnNameIn">
              <common-input
                v-model="form.columnNameIn"
                type="textarea"
                placeholder="其次匹配包含"
              />
            </el-form-item>
            <el-form-item label="注解包含" prop="columnRemarkIn">
              <common-input
                v-model="form.columnRemarkIn"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="注解排除" prop="columnRemarkEx">
              <common-input
                v-model="form.columnRemarkEx"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="内容特征" name="4">
            <el-form-item label="内容枚举" prop="contentEnum">
              <common-input
                :maxlength="5000"
                v-model="form.contentEnum"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="内容结尾" prop="contentEnd">
              <common-input
                v-model="form.contentEnd"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="正则表达式" name="5">
            <el-form-item label="正则表达式">
              <common-input
                :maxlength="2000"
                v-model="form.sensitiveContent"
                type="textarea"
                :verify="false"
                placeholder="请输入"
              />
            </el-form-item>
            <!--            <el-form-item label="扩展正则1" prop="sensitiveRex1">
              <common-input v-model="form.sensitiveRex1" type="textarea" />
            </el-form-item>
            <el-form-item label="扩展正则2" prop="sensitiveRex2">
              <common-input v-model="form.sensitiveRex2" type="textarea" />
            </el-form-item>
            <el-form-item label="扩展正则3" prop="sensitiveRex3">
              <common-input v-model="form.sensitiveRex3" type="textarea" />
            </el-form-item>
            <el-form-item label="扩展正则4" prop="sensitiveRex4">
              <common-input v-model="form.sensitiveRex4" type="textarea" />
            </el-form-item>
            <el-form-item label="扩展正则5" prop="sensitiveRex5">
              <common-input v-model="form.sensitiveRex5" type="textarea" />
            </el-form-item>-->
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </common-edit-dialog>
    <common-info-dialog
      :visible.sync="detailsOpen"
      @cancel="detailsOpen = false"
      :title="detailsTitle"
      :infoLoading="infoLoading"
    >
      <common-info-table>
        <common-info-table-cell label="敏感字段名称" width="50%">{{
          form.name
        }}</common-info-table-cell>
        <common-info-table-cell label="备注" width="50%">{{
          form.remark
        }}</common-info-table-cell>
        <common-info-table-cell label="固定长度" width="50%">{{
          form.length
        }}</common-info-table-cell>
        <common-info-table-cell label="长度范围" width="50%"
          >{{ form.minLength }} - {{ form.maxLength }}
        </common-info-table-cell>
        <common-info-table-cell label="字段名包含">{{
          form.columnNameIn
        }}</common-info-table-cell>
        <common-info-table-cell label="字段名排除">{{
          form.columnNameEx
        }}</common-info-table-cell>
        <common-info-table-cell label="注解包含">{{
          form.columnRemarkIn
        }}</common-info-table-cell>
        <common-info-table-cell label="注解排除">{{
          form.columnRemarkEx
        }}</common-info-table-cell>
        <common-info-table-cell label="内容枚举">{{
          form.contentEnum
        }}</common-info-table-cell>
        <common-info-table-cell label="内容结尾">{{
          form.contentEnd
        }}</common-info-table-cell>
        <common-info-table-cell label="正则表达式">{{
          form.sensitiveContent
        }}</common-info-table-cell>
        <!--        <common-info-table-cell label="扩展正则1">{{
            form.sensitiveRex1
          }}</common-info-table-cell>
        <common-info-table-cell label="扩展正则2">{{
            form.sensitiveRex2
          }}</common-info-table-cell>
        <common-info-table-cell label="扩展正则3">{{
            form.sensitiveRex3
          }}</common-info-table-cell>
        <common-info-table-cell label="扩展正则4">{{
            form.sensitiveRex4
          }}</common-info-table-cell>
        <common-info-table-cell label="扩展正则5">{{
            form.sensitiveRex5
          }}</common-info-table-cell>-->
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import {
  listWords,
  getWords,
  delWords,
  addWords,
  updateWords,
  updateStatus,
  deleteForCheck,
} from "@/api/datascan/sensitivewords/words";
import BaseList from "@/mixins/BaseList";

export default {
  name: "Words",
  mixins: [BaseList],
  components: {},
  data() {
    return {
      infoUpdateLoading: false,
      infoLoading: false,
      key: "wordId",
      buttonLoading: false,
      activeName: "1",
      lengthType: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 敏感字段表格数据
      wordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailsOpen: false,
      detailsTitle: "",

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {
        wordId: null,
        name: null,
        length: null,
        maxLength: null,
        minLength: null,
        columnRemarkIn: null,
        columnNameIn: null,
        columnRemarkEx: null,
        columnNameEx: null,
        isNum: null,
        contentEnum: null,
        contentEnd: null,
        contentFeature: null,
        algorithm: null,
        sensitiveContent: null,
        sensitiveRex1: null,
        sensitiveRex2: null,
        sensitiveRex3: null,
        sensitiveRex4: null,
        sensitiveRex5: null,
        reference: null,
        matchType: null,
        status: 0,
        createTime: null,
        updateTime: null,
        remark: null,
        delFlag: null,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入敏感字段名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let status = row.status == "0" ? "1" : "0";
        updateStatus({ wordId: row.wordId, status: status })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              this.getList();
              resolve(res);
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    changeLengthType(value) {
      this.lengthType = value;
      if (value === 0) {
        this.form.minLength = undefined;
        this.form.maxLength = undefined;
      }
      if (value === 1) {
        this.form.length = undefined;
      }
    },
    /** 查询敏感字段列表 */
    getList() {
      this.loading = true;
      listWords(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.wordsList = res.data.dataList.reduce((r, c) => {
              r.push({ ...c, isDisabledForShake: false });
              return r;
            }, []);
            this.total = res.data.totalCount;
          } else {
            this.wordsList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.detailsOpen = false;
      this.reset();
      this.lengthType = null;
    },
    // 表单重置
    reset() {
      this.form = {
        wordId: null,
        name: null,
        length: null,
        maxLength: null,
        minLength: null,
        columnRemarkIn: null,
        columnNameIn: null,
        columnRemarkEx: null,
        columnNameEx: null,
        isNum: null,
        contentEnum: null,
        contentEnd: null,
        contentFeature: null,
        algorithm: null,
        sensitiveContent: null,
        sensitiveRex1: null,
        sensitiveRex2: null,
        sensitiveRex3: null,
        sensitiveRex4: null,
        sensitiveRex5: null,
        reference: null,
        matchType: null,
        status: 0,
        createTime: null,
        updateTime: null,
        remark: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.wordId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.activeName = "1";
      this.lengthType = null;
      this.open = true;
      this.title = "新增敏感字段";
      this.infoUpdateLoading = false;
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      if (row.status == 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
        return;
      }
      this.reset();
      this.lengthType = row.length
        ? 0
        : row.minLength ||
          row.minLength === 0 ||
          row.maxLength ||
          row.maxLength === 0
        ? 1
        : null;
      this.getWords(row, 1);
    },
    getWords(row, n) {
      // 1:编辑  2详情
      const wordId = row.wordId || this.ids;
      if (n !== 1) {
        this.detailsOpen = true;
        this.detailsTitle = "敏感字段详情";
      } else {
        this.open = true;
        this.title = "编辑敏感字段";
      }
      this.detail(wordId);
    },
    detail(wordId) {
      this.infoLoading = true;
      this.infoUpdateLoading = true;
      getWords({ wordId }).then((res) => {
        if (res && res.code === 200) {
          this.form = Object.assign({}, res.data, {
            length: res.data.length ? parseInt(res.data.length) : null,
            minLength:
              !res.data.length && res.data.minLength
                ? parseInt(res.data.minLength)
                : null,
            maxLength:
              !res.data.length && res.data.maxLength
                ? parseInt(res.data.maxLength)
                : null,
          });
          this.infoLoading = false;
          this.infoUpdateLoading = false;
        } else {
          this.$GlobalErrorConfirm("获取信息失败", res.msg, "重新加载").then(
            () => {
              this.detail(wordId);
            }
          );
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        let params = {
          ...this.form,
          createTime: undefined,
          updateTime: undefined,
          delFlag: undefined,
          checkFlag: undefined,
          length: this.form.length,
          minLength: this.form.minLength,
          maxLength: this.form.maxLength,
          matchType: this.form.sensitiveContent ? 1 : null,
        };

        if (valid) {
          this.buttonLoading = true;
          if (this.form.wordId != null) {
            updateWords(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open = false;
                  this.queryParams.pageNum = 1;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addWords(params)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.open = false;
                  this.queryParams.pageNum = 1;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    deleteData(row) {
      if (row) {
        if (row && row.status == 0) {
          this.$GlobalErrorConfirm("刪除失败", "启用状态下不允许刪除");
          return;
        }
        const wordId = row.wordId;
        this.$GlobalDeleteConfirm()
          .then(() => {
            delWords({ wordId }).then((res) => {
              if (res && res.code == 200) {
                this.$GlobalSuccessMessage("删除成功");
                if (
                  this.queryParams.pageNum > 1 &&
                  wordId.split(",").length === this.wordsList.length
                ) {
                  this.queryParams.pageNum -= 1;
                }
                this.getList();
              } else {
                this.$GlobalErrorConfirm("删除失败", res.msg);
              }
            });
          })
          .catch(() => {});
      } else {
        let status = this.wordsList.find(
          (v) => this.ids.includes(v.wordId) && v.status === 0
        );
        if (status) {
          this.$GlobalErrorConfirm("删除失败", "状态已启用无法删除");
          return;
        }
        const wordId = this.ids.join(",");
        // console.log(wordId);
        this.$GlobalDeleteConfirm()
          .then(() => {
            delWords({ wordId }).then((res) => {
              if (res && res.code == 200) {
                this.$GlobalSuccessMessage("删除成功");
                if (
                  this.queryParams.pageNum > 1 &&
                  wordId.split(",").length === this.wordsList.length
                ) {
                  this.queryParams.pageNum -= 1;
                }
                this.getList();
              } else {
                this.$GlobalErrorConfirm("删除失败", res.msg);
              }
            });
          })
          .catch(() => {});
      }
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ wordId: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
};
</script>
<style lang="scss">
.addOrEditClass {
  max-height: 66%;
  overflow-y: auto;

  .lengthRang {
    display: flex;

    .rangLine {
      width: 40px;
      text-align: center;
    }
  }
}
</style>
